package org.phona.object;

import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import org.phona.OnUserEventListener;
import org.phona.R;

import android.content.Context;
import android.database.Cursor;
import android.graphics.Color;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class ContactsAdapter extends BaseAdapter {

	LayoutInflater li;
	Context context;

	ContactManager cm;
	OnUserEventListener onUserEventListener;

	public static final String TAG = "ContactsAdapter";


	public ContactsAdapter(Context context){
		this.context = context;
		li = LayoutInflater.from(context);	
		cm = new ContactManager(context);


	}

	public void init(){
		//Long start = System.currentTimeMillis();
		cm.init();
		//Log.i(TAG,"Loading contacts in :"+(System.currentTimeMillis()-start));

	}


	/*	Cursor getContactsFromContentProvider(){

		Cursor c = context.getContentResolver().query(Data.CONTENT_URI,
				new String[] {Data._ID,Data.DISPLAY_NAME, Phone.NUMBER,Phone.TYPE, Phone.LABEL,Phone.IS_PRIMARY},
				Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "' AND "+
				ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '1' "


				//Phone.TYPE+"='"+Phone.TYPE_HOME+"' AND "+
				//Data.DISPLAY_NAME+" like '%si%'",
				null, null);
				return c;
	}*/



	@Override
	public int getCount() {

		//return filter==null?contactList.size():filtredContactList.size();
		return cm.getCount();
	}

	@Override
	public Object getItem(int position) {
		Log.i(TAG,"gettingItem pos="+position);	
		//return filter==null?contactList.get(position):filtredContactList.get(position);
		return cm.getItem(position);
	}

	@Override
	public long getItemId(int position) {
		Log.i(TAG,"gettingItemId pos="+position);
		return position;
	}



	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		Long start = System.currentTimeMillis();
		convertView = li.inflate(R.layout.contact_row, null);

		//fillText(convertView, position, (filter==null?contactList.get(position):filtredContactList.get(position)));		
		fillText(convertView, position, (Contact)cm.getItem(position));
		Log.v(TAG,"getView in :"+(System.currentTimeMillis()-start));
		return convertView;
	}

	public void filter(String filter){
		cm.filter(filter);
	}
	

	void fillText(	View convertView, int position, Contact contact) {
		Long start = System.currentTimeMillis();
		final Contact finalContact = contact;
		LinearLayout container = (LinearLayout)convertView.findViewById(R.id.text_container);
		Boolean highlight=true;
		TextView tv = null;

		if(cm.isFilterEnabled()){
			for(String chars : getWordCuted(contact.getName(),cm.getMatchedString(contact))){

				if(chars.length()>0){
					tv = new TextView(context);
					tv.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
					tv.setTextSize(TypedValue.COMPLEX_UNIT_DIP,15);
					tv.setText(chars);
					container.addView(tv);
				}


				if(highlight){
					if(chars.length()>0){
						tv.setTextColor(Color.parseColor("#FF6600"));
					}
					highlight=false;				
				}else{
					highlight=true;				
				}
			}
		}else{
			tv = new TextView(context);
			tv.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
			tv.setTextSize(TypedValue.COMPLEX_UNIT_DIP,15);
			tv.setText(contact.getName());
			container.addView(tv);
		}


		//text1.setText(list.get(position).getName());
		((TextView)convertView.findViewById(R.id.text2)).setText(contact.getPrimaryPhone());
		final OnUserEventListener ouel = this.onUserEventListener;

		((ImageView)convertView.findViewById(R.id.call)).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				ouel.onEvent(finalContact);
			}
		});
		Log.v(TAG,"Fill Text in :"+(System.currentTimeMillis()-start));
	}




	List<String> getWordCuted(String name, List<String> toHighlightCharsList) {		
		//alway return a list where the first element is highligted
		//if the first element should not be, return empty string first
		List<String> result = new ArrayList<String>();

		List<Boolean> highlightedChar = new Vector<Boolean>();
		for(Integer i=0,n=name.length();i<n;i++){
			highlightedChar.add(Boolean.FALSE);
		}
		for(String t : toHighlightCharsList){
			for(Integer i=name.indexOf(t),n=name.indexOf(t)+t.length();i<n;i++){
				highlightedChar.set(i,Boolean.TRUE);
			}
		}
		String currentChars = "";
		for(Integer i=0,n=name.length();i<n;i++){
			if(i==0){
				if(highlightedChar.get(0)==false){
					result.add(currentChars);
				}
				currentChars+=name.charAt(i);
			}else if(highlightedChar.get(i)==highlightedChar.get(i-1)){
				currentChars+=name.charAt(i);
			}else{
				result.add(currentChars);
				currentChars=new String()+name.charAt(i);
			}
		}
		result.add(currentChars);

		return result;
	}



	public void addOnUserEventListener(OnUserEventListener onUserEventListener) {
		this.onUserEventListener = onUserEventListener;
	}

}
